// center.js
// 导入请求工具
const { get } = require('../../utils/request');
const app = getApp();

Page({
  data: {
    userInfo: {}, // 用户信息
    orderStats: {
      unpaid: 0, // 待付款
      unshipped: 0, // 待发货
      unreceived: 0, // 待收货
      unrated: 0, // 待评价
      after_sale: 0 // 售后
    }
  },

  onShow: function() {
    // 页面显示时，加载用户数据
    this.loadUserData();
  },

  /**
   * 加载用户数据
   */
  loadUserData: function() {
    // 检查登录状态
    if (!app.globalData.isLoggedIn) {
      // 未登录状态，显示默认信息
      this.setData({
        userInfo: {},
        orderStats: {
          unpaid: 0,
          unshipped: 0,
          unreceived: 0,
          unrated: 0,
          after_sale: 0
        }
      });
      return;
    }

    wx.showLoading({
      title: '加载中',
    });

    // 并发请求用户信息和订单统计
    Promise.all([
      this.loadUserInfo(),
      this.loadOrderStats()
    ])
      .then(() => {
        wx.hideLoading();
      })
      .catch(err => {
        wx.hideLoading();
        console.error('加载用户数据失败', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
  },

  /**
   * 加载用户信息
   */
  loadUserInfo: function() {
    return new Promise((resolve, reject) => {
      get('/api/user/info/')
        .then(res => {
          const userInfo = res || {};
          this.setData({
            userInfo: userInfo
          });
          resolve();
        })
        .catch(err => {
          console.error('加载用户信息失败', err);
          reject(err);
        });
    });
  },

  /**
   * 加载订单统计
   */
  loadOrderStats: function() {
    return new Promise((resolve, reject) => {
      get('/api/orders/stats/')
        .then(res => {
          const orderStats = res || {
            unpaid: 0,
            unshipped: 0,
            unreceived: 0,
            unrated: 0,
            after_sale: 0
          };
          this.setData({
            orderStats: orderStats
          });
          resolve();
        })
        .catch(err => {
          console.error('加载订单统计失败', err);
          reject(err);
        });
    });
  },

  /**
   * 查看优惠券
   */
  viewCoupons: function() {
    if (!app.globalData.isLoggedIn) {
      this.loginRequired();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/user/coupons'
    });
  },

  /**
   * 查看我的积分
   */
  viewMyPoints: function() {
    if (!app.globalData.isLoggedIn) {
      this.loginRequired();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/user/points'
    });
  },

  /**
   * 查看我的钱包
   */
  viewMyWallet: function() {
    if (!app.globalData.isLoggedIn) {
      this.loginRequired();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/user/wallet'
    });
  },

  /**
   * 查看全部订单
   */
  viewAllOrders: function() {
    if (!app.globalData.isLoggedIn) {
      this.loginRequired();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/order/list'
    });
  },

  /**
   * 按状态查看订单
   */
  viewOrdersByStatus: function(e) {
    if (!app.globalData.isLoggedIn) {
      this.loginRequired();
      return;
    }
    
    const status = e.currentTarget.dataset.status;
    wx.navigateTo({
      url: `/pages/order/list?status=${status}`
    });
  },

  /**
   * 查看我的收藏
   */
  viewMyFavorites: function() {
    if (!app.globalData.isLoggedIn) {
      this.loginRequired();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/user/favorites'
    });
  },

  /**
   * 查看收货地址
   */
  viewAddressList: function() {
    if (!app.globalData.isLoggedIn) {
      this.loginRequired();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/address/list'
    });
  },

  /**
   * 联系客服
   */
  viewCustomerService: function() {
    wx.showToast({
      title: '暂未实现客服功能',
      icon: 'none'
    });
  },

  /**
   * 关于我们
   */
  viewAboutUs: function() {
    wx.navigateTo({
      url: '/pages/user/about'
    });
  },

  /**
   * 帮助中心
   */
  viewHelpCenter: function() {
    wx.navigateTo({
      url: '/pages/user/help'
    });
  },

  /**
   * 意见反馈
   */
  viewFeedback: function() {
    wx.navigateTo({
      url: '/pages/user/feedback'
    });
  },

  /**
   * 查看设置
   */
  viewSettings: function() {
    wx.navigateTo({
      url: '/pages/user/settings'
    });
  },

  /**
   * 登录提示
   */
  loginRequired: function() {
    wx.showModal({
      title: '请登录',
      content: '此功能需要登录后使用，是否立即登录？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/user/login'
          });
        }
      }
    });
  }
});